#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <strings.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char*argv[]){

	int sockfd;
	struct sockaddr_in addr;
	char buf[BUFSIZ] = {};

	/*参数检查*/
	if(argc < 3){
		fprintf(stderr, "%s<addr><port>", argv[0]);
		exit(EXIT_FAILURE);
	}
	/*创造套接字*/

	if( (sockfd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0){
		perror("socket");
		exit(EXIT_FAILURE);
	}

	/*设置通信结构体*/
	bzero(&addr, sizeof(addr));
	addr.sin_port = htons( atoi(argv[2]) );
	addr.sin_family = AF_INET;

	if(inet_aton(argv[1], &addr.sin_addr) == 0){
		fprintf(stderr, "Invalid address\n");
		exit(EXIT_FAILURE);
	}

	/*绑定通信结构体*/
	if(bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1){
		perror("bind");
		exit(EXIT_FAILURE);
	}
	while(1){
		bzero(buf, BUFSIZ);
		recvfrom(sockfd, buf, BUFSIZ, 0, NULL, NULL);
		printf("[%s:%d]buf = %s\n", 
				inet_aton(addr.sin_addr), ntohs(addr.sin_port), buf);
	}

	close(sockfd);
	return 0;
}
